<template>
  <base-layout>
    <div class="page-container">
      <!-- 搜索区域 -->
      <a-card class="search-card" :bordered="false">
        <div class="search-header">
          <div class="left">
            <h2>成就搜索</h2>
            <span class="desc">您可以搜索成就名称、类型等信息</span>
          </div>
          <div class="search-box">
            <a-input-search
              v-model:value="searchText"
              placeholder="请输入成就名称"
              style="width: 360px"
              @search="handleSearch"
              size="large"
            >
              <template #prefix>
                <search-outlined />
              </template>
            </a-input-search>
          </div>
        </div>

        <!-- 分类选择 -->
        <div class="filter-area">
          <div class="filter-item">
            <span class="label">类型：</span>
            <a-radio-group v-model:value="achievementType" @change="handleTypeChange" button-style="solid">
              <a-radio-button value="all">全部</a-radio-button>
              <a-radio-button value="certificate">证书</a-radio-button>
              <a-radio-button value="competition">竞赛</a-radio-button>
              <a-radio-button value="software">软著</a-radio-button>
              <a-radio-button value="video">影片</a-radio-button>
              <a-radio-button value="book">读书</a-radio-button>
              <a-radio-button value="activity">活动</a-radio-button>
            </a-radio-group>
          </div>
          <div class="filter-item">
            <span class="label">审核状态：</span>
            <a-radio-group v-model:value="achievementStatus" @change="handleStatusChange" button-style="solid">
              <a-radio-button value="all">全部</a-radio-button>
              <a-radio-button value="pending">待审核</a-radio-button>
              <a-radio-button value="approved">已通过</a-radio-button>
              <a-radio-button value="rejected">已驳回</a-radio-button>
            </a-radio-group>
          </div>
        </div>
      </a-card>

      <!-- 统计卡片 -->
      <div class="stats-container">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card class="stat-card">
              <statistic
                title="待审核"
                :value="stats.pending"
                :value-style="{ color: '#faad14' }"
              >
                <template #prefix>
                  <field-time-outlined />
                </template>
              </statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <statistic
                title="今日审核"
                :value="stats.todayReviewed"
                :value-style="{ color: '#1890ff' }"
              >
                <template #prefix>
                  <calendar-outlined />
                </template>
              </statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <statistic
                title="本月通过"
                :value="stats.monthlyApproved"
                :value-style="{ color: '#52c41a' }"
              >
                <template #prefix>
                  <check-outlined />
                </template>
              </statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <statistic
                title="通过率"
                :value="stats.approvalRate"
                suffix="%"
                :precision="2"
                :value-style="{ color: '#eb2f96' }"
              >
                <template #prefix>
                  <percentage-outlined />
                </template>
              </statistic>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 成就列表 -->
      <a-card class="table-card" :bordered="false">
        <template #title>
          <div class="table-header">
            <span class="title">成就审核列表</span>
            <span class="desc">共 {{ pagination.total }} 个成就</span>
          </div>
        </template>
        <a-table
          :columns="columns"
          :data-source="achievements"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: 1300 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <div class="action-buttons">
                <a-tooltip title="查看详情">
                  <a @click="handleView(record)" class="action-link primary">
                    <eye-outlined />查看
                  </a>
                </a-tooltip>
                <template v-if="record.status === 'pending'">
                  <a-tooltip title="通过">
                    <a @click="handleApprove(record)" class="action-link approve">
                      <check-outlined />通过
                    </a>
                  </a-tooltip>
                  <a-tooltip title="驳回">
                    <a @click="handleReject(record)" class="action-link reject">
                      <close-outlined />驳回
                    </a>
                  </a-tooltip>
                </template>
                <a-tooltip title="删除">
                  <a-popconfirm
                    title="确定要删除这个成就吗？"
                    okText="确定"
                    cancelText="取消"
                    @confirm="handleDelete(record)"
                  >
                    <a class="action-link delete">
                      <delete-outlined />删除
                    </a>
                  </a-popconfirm>
                </a-tooltip>
              </div>
            </template>
            <template v-else-if="column.key === 'type'">
              <a-tag :color="getTypeColor(record.type)">
                {{ record.type }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'points'">
              <span class="points">+{{ record.points }}</span>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 审核对话框 -->
    <a-modal
      v-model:visible="reviewModal.visible"
      :title="reviewModal.type === 'approve' ? '通过审核' : '驳回原因'"
      @ok="handleReviewSubmit"
      :confirmLoading="reviewModal.loading"
    >
      <a-form :model="reviewModal.form">
        <a-form-item v-if="reviewModal.type === 'reject'" label="驳回原因" :rules="[{ required: true, message: '请输入驳回原因' }]">
          <a-textarea
            v-model:value="reviewModal.form.reason"
            :rows="4"
            placeholder="请输入驳回原因，将通知给学生"
          />
        </a-form-item>
        <a-form-item label="审核备注" :rules="[{ required: false }]">
          <a-textarea
            v-model:value="reviewModal.form.comment"
            :rows="3"
            placeholder="可选填写审核备注"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </base-layout>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { message, Statistic, Modal } from 'ant-design-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import {
  SearchOutlined,
  EyeOutlined,
  DeleteOutlined,
  CheckOutlined,
  CloseOutlined,
  FieldTimeOutlined,
  CalendarOutlined,
  PercentageOutlined
} from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { achievementApi } from '@/api'

export default {
  name: 'AchievementManage',
  components: {
    BaseLayout,
    Statistic,
    SearchOutlined,
    EyeOutlined,
    DeleteOutlined,
    CheckOutlined,
    CloseOutlined,
    FieldTimeOutlined,
    CalendarOutlined,
    PercentageOutlined
  },
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const searchText = ref('')
    const achievementType = ref('all')
    const achievementStatus = ref('all')
    const achievements = ref([])
    const pagination = ref({
      current: 1,
      pageSize: 10,
      total: 0,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: (total) => `共 ${total} 条记录`
    })

    // 统计数据
    const stats = reactive({
      pending: 15,
      todayReviewed: 8,
      monthlyApproved: 128,
      approvalRate: 95.5
    })

    // 审核对话框数据
    const reviewModal = reactive({
      visible: false,
      type: 'approve', // 'approve' | 'reject'
      loading: false,
      currentRecord: null,
      form: {
        reason: '',
        comment: ''
      }
    })

    const columns = [
      {
        title: '学生姓名',
        dataIndex: 'studentName',
        key: 'studentName',
        width: 100,
        fixed: 'left'
      },
      {
        title: '学号',
        dataIndex: 'studentId',
        key: 'studentId',
        width: 100
      },
      {
        title: '成就名称',
        dataIndex: 'name',
        key: 'name',
        width: 180,
        ellipsis: true
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 100
      },
      {
        title: '获得时间',
        dataIndex: 'achieveTime',
        key: 'achieveTime',
        width: 120
      },
      {
        title: '提交时间',
        dataIndex: 'submitTime',
        key: 'submitTime',
        width: 160
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100
      },
      {
        title: '操作',
        key: 'action',
        width: 280,
        fixed: 'right',
        align: 'center'
      }
    ]

    const getTypeColor = (type) => {
      const colors = {
        '证书': 'blue',
        '竞赛': 'green',
        '软著': 'purple',
        '影片': 'orange',
        '读书': 'cyan',
        '活动': 'magenta'
      }
      return colors[type] || 'default'
    }

    const getStatusColor = (status) => {
      const colors = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'error'
      }
      return colors[status] || 'default'
    }

    const getStatusText = (status) => {
      const texts = {
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已驳回'
      }
      return texts[status] || status
    }

    const fetchAchievements = () => {
      loading.value = true
      // 模拟API调用
      setTimeout(() => {
        // 根据搜索条件过滤数据
        const allData = [
          {
            id: 1,
            studentName: '张三',
            studentId: '2021001',
            name: 'CET-6 优秀成绩',
            type: '证书',
            achieveTime: '2024-03-10',
            submitTime: '2024-03-15 14:30:00',
            status: 'pending'
          },
          {
            id: 2,
            studentName: '李四',
            studentId: '2021002',
            name: '蓝桥杯省赛一等奖',
            type: '竞赛',
            achieveTime: '2024-03-08',
            submitTime: '2024-03-14 09:30:00',
            status: 'approved'
          },
          {
            id: 3,
            studentName: '王五',
            studentId: '2021003',
            name: '校园二手交易平台',
            type: '软著',
            achieveTime: '2024-03-05',
            submitTime: '2024-03-12 10:30:00',
            status: 'pending'
          },
          {
            id: 4,
            studentName: '赵六',
            studentId: '2021004',
            name: 'Vue3实战教程',
            type: '影片',
            achieveTime: '2024-03-01',
            submitTime: '2024-03-11 16:30:00',
            status: 'approved'
          },
          {
            id: 5,
            studentName: '钱七',
            studentId: '2021005',
            name: '深入理解Vue.js实战',
            type: '读书',
            achieveTime: '2024-02-28',
            submitTime: '2024-03-10 11:30:00',
            status: 'pending'
          },
          {
            id: 6,
            studentName: '孙八',
            studentId: '2021006',
            name: '校园公益活动志愿者',
            type: '活动',
            achieveTime: '2024-02-25',
            submitTime: '2024-03-09 14:30:00',
            status: 'approved'
          }
        ]

        // 应用搜索过滤
        let filteredData = allData

        // 按名称搜索
        if (searchText.value) {
          filteredData = filteredData.filter(item => 
            item.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
            item.studentName.toLowerCase().includes(searchText.value.toLowerCase()) ||
            item.studentId.includes(searchText.value)
          )
        }

        // 按类型筛选
        if (achievementType.value !== 'all') {
          filteredData = filteredData.filter(item => {
            const typeMap = {
              'certificate': '证书',
              'competition': '竞赛',
              'software': '软著',
              'video': '影片',
              'book': '读书',
              'activity': '活动'
            }
            return item.type === typeMap[achievementType.value]
          })
        }

        // 按状态筛选
        if (achievementStatus.value !== 'all') {
          filteredData = filteredData.filter(item => item.status === achievementStatus.value)
        }

        // 更新统计数据
        stats.pending = filteredData.filter(item => item.status === 'pending').length
        stats.todayReviewed = filteredData.filter(item => {
          const today = new Date().toISOString().split('T')[0]
          return item.status !== 'pending' && item.submitTime.startsWith(today)
        }).length
        stats.monthlyApproved = filteredData.filter(item => {
          const thisMonth = new Date().toISOString().slice(0, 7)
          return item.status === 'approved' && item.submitTime.startsWith(thisMonth)
        }).length
        const totalReviewed = filteredData.filter(item => item.status !== 'pending').length
        stats.approvalRate = totalReviewed ? 
          (filteredData.filter(item => item.status === 'approved').length / totalReviewed * 100).toFixed(2) : 
          0

        achievements.value = filteredData
        pagination.value.total = filteredData.length
        loading.value = false
      }, 500)
    }

    const handleSearch = (value) => {
      searchText.value = value
      pagination.value.current = 1
      fetchAchievements()
    }

    const handleTypeChange = () => {
      pagination.value.current = 1
      fetchAchievements()
    }

    const handleStatusChange = () => {
      pagination.value.current = 1
      fetchAchievements()
    }

    const handleView = (record) => {
      router.push({
        name: 'achievement-detail',
        params: { id: record.id }
      })
    }

    const handleDelete = async (record) => {
      try {
        await achievementApi.deleteAchievement(record.id)
        message.success('删除成功')
        fetchAchievements()
      } catch (error) {
        message.error('删除失败')
      }
    }

    const handleTableChange = (pag) => {
      pagination.value.current = pag.current
      pagination.value.pageSize = pag.pageSize
      fetchAchievements()
    }

    const handleApprove = (record) => {
      reviewModal.type = 'approve'
      reviewModal.currentRecord = record
      reviewModal.form.reason = ''
      reviewModal.form.comment = ''
      reviewModal.visible = true
    }

    const handleReject = (record) => {
      reviewModal.type = 'reject'
      reviewModal.currentRecord = record
      reviewModal.form.reason = ''
      reviewModal.form.comment = ''
      reviewModal.visible = true
    }

    const handleReviewSubmit = async () => {
      if (reviewModal.type === 'reject' && !reviewModal.form.reason.trim()) {
        message.error('请输入驳回原因')
        return
      }

      reviewModal.loading = true
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        const actionText = reviewModal.type === 'approve' ? '通过' : '驳回'
        message.success(`审核${actionText}成功`)
        reviewModal.visible = false
        fetchAchievements()
      } catch (error) {
        message.error(`审核${actionText}失败`)
      } finally {
        reviewModal.loading = false
      }
    }

    onMounted(() => {
      fetchAchievements()
    })

    return {
      loading,
      searchText,
      achievementType,
      achievementStatus,
      achievements,
      columns,
      pagination,
      stats,
      reviewModal,
      getTypeColor,
      getStatusColor,
      getStatusText,
      handleSearch,
      handleTypeChange,
      handleStatusChange,
      handleView,
      handleDelete,
      handleTableChange,
      handleApprove,
      handleReject,
      handleReviewSubmit
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-header .left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.search-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
}

.search-header .desc {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

.search-box {
  display: flex;
  gap: 16px;
}

.filter-area {
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item .label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
}

.stats-container {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.table-card {
  border-radius: 8px;
}

.table-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-header .title {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.table-header .desc {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: nowrap;
  white-space: nowrap;
}

.action-link {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
  white-space: nowrap;
  min-width: 64px;
  justify-content: center;
}

.action-link.primary {
  color: #1890ff;
  background: rgba(24, 144, 255, 0.1);
}

.action-link.primary:hover {
  color: #40a9ff;
  background: rgba(24, 144, 255, 0.2);
}

.action-link.approve {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
}

.action-link.approve:hover {
  color: #73d13d;
  background: rgba(82, 196, 26, 0.2);
}

.action-link.reject {
  color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
}

.action-link.reject:hover {
  color: #ff7875;
  background: rgba(255, 77, 79, 0.2);
}

.action-link.delete {
  color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
}

.action-link.delete:hover {
  color: #ff7875;
  background: rgba(255, 77, 79, 0.2);
}

.points {
  color: #52c41a;
  font-weight: 500;
}

:deep(.ant-table) {
  overflow-x: auto;
}

:deep(.ant-table-thead > tr > th) {
  white-space: nowrap;
}

:deep(.ant-table-body) {
  overflow-x: auto !important;
}

:deep(.ant-table-cell) {
  font-size: 14px;
  white-space: nowrap;
}

:deep(.ant-radio-group) {
  display: flex;
}

:deep(.ant-radio-button-wrapper) {
  min-width: 88px;
  text-align: center;
}

:deep(.ant-statistic-title) {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

:deep(.ant-statistic-content) {
  font-size: 24px;
  font-weight: 600;
}

:deep(.ant-statistic-content-prefix) {
  margin-right: 8px;
}

:deep(.ant-modal-body) {
  padding: 24px;
}
</style> 